package com.fenghen.demo03.controller;

import org.apache.commons.net.PrintCommandListener;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;

import java.awt.*;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.PrintWriter;

public class FtpTestController {

    public static void main(String[] args) {
        String server = "127.0.0.1";
        int port = 21;
        String user = "sjh";  // FTP 用户名
        String password = "1108403"; // 设置适当的密码
        String localDir = "C:/Users/18756/Desktop/20250110"; // 本地文件夹路径
        String remoteDir = "F:/ftpshare"; // 远程目标目录（使用正斜杠）

        FTPClient ftpClient = new FTPClient();

        try {
            // 启用调试
            ftpClient.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out)));

            // 连接到FTP服务器
            ftpClient.connect(server, port);
            ftpClient.login(user, password);
            ftpClient.enterLocalPassiveMode();
            ftpClient.setFileType(FTP.BINARY_FILE_TYPE);

            // 上传文件
            File localDirectory = new File(localDir);
            uploadFiles(ftpClient, localDirectory, remoteDir);

            System.out.println("文件上传成功！");
        } catch (IOException ex) {
            System.out.println("错误: " + ex.getMessage());
        } finally {
            try {
                if (ftpClient.isConnected()) {
                    ftpClient.logout();
                    ftpClient.disconnect();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }

    private static void uploadFiles(FTPClient ftpClient, File localDir, String remoteDir) throws IOException {
        // 切换到目标远程目录
        if (!ftpClient.changeWorkingDirectory(remoteDir)) {
            System.out.println("无法进入远程目录: " + remoteDir);
            return; // 如果无法进入目录，则直接返回
        } else {
            System.out.println("已进入远程目录: " + remoteDir);
        }

        // 遍历本地文件夹中的所有文件
        File[] files = localDir.listFiles();
        if (files != null) {
            for (File file : files) {
                if (file.isFile()) {
                    // 上传文件
                    try (FileInputStream fis = new FileInputStream(file)) {
                        // 使用文件名上传到远程目录
                        boolean done = ftpClient.storeFile(file.getName(), fis);
                        if (done) {
                            System.out.println("已上传文件: " + file.getName());
                        } else {
                            System.out.println("未能上传文件: " + file.getName());
                        }
                    }
                }
            }
        }
    }
}
